<template>
  <div class="address-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="icon-arrow-left"></i>
        </button>
        <h1 class="page-title">收货地址</h1>
      </div>
      <button class="add-btn" @click="showAddDialog = true">
        <i class="icon-plus"></i>
        新增地址
      </button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list" v-if="addresses.length > 0">
      <div 
        class="address-item" 
        v-for="address in addresses" 
        :key="address.id"
        :class="{ 'default': address.isDefault }"
      >
        <div class="address-content" @click="selectAddress(address)">
          <div class="address-header">
            <span class="receiver-name">{{ address.receiverName }}</span>
            <span class="receiver-phone">{{ address.receiverPhone }}</span>
            <span v-if="address.isDefault" class="default-tag">默认</span>
            <span v-if="address.addressTag" class="address-tag">{{ address.addressTag }}</span>
          </div>
          <div class="address-detail">
            {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
          </div>
        </div>
        <div class="address-actions">
          <button class="action-btn edit" @click.stop="editAddress(address)">
            <i class="icon-edit"></i>
          </button>
          <button class="action-btn delete" @click.stop="deleteAddress(address)">
            <i class="icon-delete"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <div class="empty-icon">
        <i class="icon-address"></i>
      </div>
      <p class="empty-text">暂无收货地址</p>
      <button class="add-first-btn" @click="showAddDialog = true">
        添加第一个地址
      </button>
    </div>

    <!-- 添加/编辑地址弹窗 -->
    <div class="dialog-overlay" v-if="showAddDialog || showEditDialog" @click="closeDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>{{ isEdit ? '编辑地址' : '新增地址' }}</h3>
          <button class="close-btn" @click="closeDialog">
            <i class="icon-close"></i>
          </button>
        </div>
        
        <form class="address-form" @submit.prevent="submitAddress">
          <div class="form-group">
            <label>收货人姓名</label>
            <input 
              v-model="formData.receiverName" 
              type="text" 
              placeholder="请输入收货人姓名"
              required
            />
          </div>
          
          <div class="form-group">
            <label>手机号码</label>
            <input 
              v-model="formData.receiverPhone" 
              type="tel" 
              placeholder="请输入手机号码"
              required
            />
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>省份</label>
              <input 
                v-model="formData.province" 
                type="text" 
                placeholder="请输入省份"
                required
              />
            </div>
            <div class="form-group">
              <label>城市</label>
              <input 
                v-model="formData.city" 
                type="text" 
                placeholder="请输入城市"
                required
              />
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>区县</label>
              <input 
                v-model="formData.district" 
                type="text" 
                placeholder="请输入区县"
                required
              />
            </div>
            <div class="form-group">
              <label>邮政编码</label>
              <input 
                v-model="formData.postalCode" 
                type="text" 
                placeholder="请输入邮政编码"
              />
            </div>
          </div>
          
          <div class="form-group">
            <label>详细地址</label>
            <textarea 
              v-model="formData.detailAddress" 
              placeholder="请输入详细地址"
              required
            ></textarea>
          </div>
          
          <div class="form-group">
            <label>地址标签</label>
            <select v-model="formData.addressTag">
              <option value="">请选择标签</option>
              <option value="家">家</option>
              <option value="公司">公司</option>
              <option value="学校">学校</option>
              <option value="其他">其他</option>
            </select>
          </div>
          
          <div class="form-group checkbox-group">
            <label class="checkbox-label">
              <input 
                type="checkbox" 
                v-model="formData.isDefault"
              />
              <span class="checkbox-text">设为默认地址</span>
            </label>
          </div>
          
          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="closeDialog">
              取消
            </button>
            <button type="submit" class="submit-btn" :disabled="loading">
              {{ loading ? '保存中...' : '保存' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAddressStore } from '@/stores/address'
import { useUserStore } from '@/stores/user'
import type { Address } from '@/api/address'

// 路由
const router = useRouter()

// 状态管理
const addressStore = useAddressStore()
const userStore = useUserStore()

// 响应式数据
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const editingAddress = ref<Address | null>(null)
const loading = ref(false)

// 表单数据
const formData = reactive({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  postalCode: '',
  addressTag: '',
  isDefault: false
})

// 计算属性
const addresses = computed(() => addressStore.addresses)
const isEdit = computed(() => showEditDialog.value)

// 生命周期
onMounted(() => {
  loadAddresses()
})

// 方法
const loadAddresses = async () => {
  const userId = userStore.user?.id
  if (userId) {
    await addressStore.fetchAddresses(userId)
  }
}

const goBack = () => {
  router.back()
}

const selectAddress = (address: Address) => {
  // 这里可以处理地址选择逻辑
  console.log('选择地址:', address)
}

const editAddress = (address: Address) => {
  editingAddress.value = address
  showEditDialog.value = true
  // 填充表单数据
  Object.assign(formData, {
    receiverName: address.receiverName,
    receiverPhone: address.receiverPhone,
    province: address.province,
    city: address.city,
    district: address.district,
    detailAddress: address.detailAddress,
    postalCode: address.postalCode || '',
    addressTag: address.addressTag || '',
    isDefault: address.isDefault
  })
}

const deleteAddress = async (address: Address) => {
  if (!confirm('确定要删除这个地址吗？')) {
    return
  }
  
  const userId = userStore.user?.id
  if (!userId || !address.id) return
  
  const result = await addressStore.removeAddress(userId, address.id)
  if (result.success) {
    alert('删除成功')
  } else {
    alert('删除失败: ' + result.message)
  }
}

const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  editingAddress.value = null
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    receiverName: '',
    receiverPhone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    postalCode: '',
    addressTag: '',
    isDefault: false
  })
}

const submitAddress = async () => {
  loading.value = true
  
  try {
    const userId = userStore.user?.id
    if (!userId) {
      alert('用户信息不存在')
      return
    }
    
    let result
    if (isEdit.value && editingAddress.value?.id) {
      // 更新地址
      result = await addressStore.editAddress(userId, editingAddress.value.id, formData)
    } else {
      // 创建地址
      result = await addressStore.addAddress(userId, formData)
    }
    
    if (result.success) {
      alert(isEdit.value ? '更新成功' : '添加成功')
      closeDialog()
    } else {
      alert('操作失败: ' + result.message)
    }
  } catch (error) {
    console.error('提交地址失败:', error)
    alert('操作失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.address-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.address-list {
  padding: 16px;
}

.address-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.address-item.default {
  border: 2px solid #007bff;
}

.address-content {
  flex: 1;
  cursor: pointer;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.receiver-name {
  font-weight: 600;
  font-size: 16px;
}

.receiver-phone {
  color: #666;
  font-size: 14px;
}

.default-tag {
  background-color: #007bff;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.address-tag {
  background-color: #f0f0f0;
  color: #666;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.address-detail {
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.address-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.action-btn.edit {
  color: #007bff;
}

.action-btn.delete {
  color: #dc3545;
}

.action-btn:hover {
  background-color: #f0f0f0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 16px;
}

.empty-text {
  color: #666;
  margin-bottom: 20px;
}

.add-first-btn {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.address-form {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 12px;
}

.form-row .form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.checkbox-group {
  display: flex;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.checkbox-text {
  font-weight: normal;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}

.submit-btn {
  background-color: #007bff;
  color: white;
}

.submit-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style> 